import { createRouter, createWebHistory } from 'vue-router'
import routes from './constRoutes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 前置守卫函数
router.beforeEach((to, from, next) => {
  // 获取token
  let token = localStorage.getItem('token')
  if (token) {
    if (to.path == '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (to.path == '/login' || to.path == '/register') {
      next()
    } else {
      next('/login')
    }
  }

  // 开启进度条
  NProgress.start()

  // 动态变换标题
  document.title = to.meta.title
})

// 后置守卫函数
router.afterEach((to, from) => {
  // 关闭进度条
  NProgress.done()
})

export default router
